<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品编号" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入商品编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="商品简介" prop="intro">-->
<!--        <el-input-->
<!--          v-model="queryParams.intro"-->
<!--          placeholder="请输入商品简介"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="关联分类id" prop="categoryId">-->
<!--        <el-input-->
<!--          v-model="queryParams.categoryId"-->
<!--          placeholder="请输入关联分类id"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="商品主图" prop="cover">-->
<!--        <el-input-->
<!--          v-model="queryParams.cover"-->
<!--          placeholder="请输入商品主图"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="商品价格" prop="originalPrice">-->
<!--        <el-input-->
<!--          v-model="queryParams.originalPrice"-->
<!--          placeholder="请输入商品价格"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="实际价格" prop="price">-->
<!--        <el-input-->
<!--          v-model="queryParams.price"-->
<!--          placeholder="请输入实际价格"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="库存" prop="stock">-->
<!--        <el-input-->
<!--          v-model="queryParams.stock"-->
<!--          placeholder="请输入库存"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="上架状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择商品上架状态" clearable size="small">
          <el-option
            v-for="dict in dict.type.p_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:product:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:product:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:product:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品编号" align="center" prop="id" />
      <el-table-column label="商品名" align="center" prop="name" >
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <el-form label-suffix=":">
              <el-form-item label="商品名称" style="width: 250px;">
                {{ scope.row.name }}
              </el-form-item>
              <el-form-item label="商品主图">
                <el-image
                  style="width: 100px; height: 100px"
                  :src="scope.row.cover"
                  :preview-src-list="[scope.row.cover]">
                </el-image>
              </el-form-item>
              <el-form-item label="商品简介" style="width: 250px;">
                {{ scope.row.intro }}
              </el-form-item>
              <el-form-item label="商品详情" class="detail" style="width: 250px;">
                <div v-html="scope.row.detail"></div>
              </el-form-item>
            </el-form>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ scope.row.name }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
     <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.product_type" :value="scope.row.type"/>
        </template>
     </el-table-column>
     <el-table-column label="关联分类" align="center" prop="categoryName" />
     <!-- <el-table-column label="商品主图" align="center" prop="cover" /> -->
     <!-- <el-table-column label="商品详情" align="center" prop="detail" /> -->
      <el-table-column label="商品价格" align="center" prop="price" />
      <el-table-column label="库存" align="center" prop="stock" />
      <el-table-column label="是否热门" align="center" prop="isHot">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.is_hot" :value="scope.row.isHot"/>
        </template>
      </el-table-column>
      <el-table-column label="商品上架状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.p_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:product:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="openProductKeyList(scope.row)"
            v-hasPermi="['admin:productKey']"
          >查看库存</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-check"
            @click="openProductKeyAdd(scope.row)"
            v-hasPermi="['admin:productKey']"
          >录入库存</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:product:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名" />
        </el-form-item>
        <el-form-item label="商品简介" prop="intro">
          <editor v-model="form.intro" :min-height="192"/>
        </el-form-item>
        <el-form-item label="商品类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio
              v-for="dict in dict.type.product_type"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="关联分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择关联分类">
            <el-option
              v-for="category in categroys"
              :key="category.id"
              :label="category.categoryName"
              :value="category.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品主图" prop="cover">
          <el-input v-model="form.cover" v-if="false" />
          <ImageUpload :value="form.cover" :fileSize="20" :limit="1" @input="uploadImage" />
        </el-form-item>
        <el-form-item label="商品详情" prop="detail">
          <editor v-model="form.detail" :min-height="192"/>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input type="number" v-model="form.price" placeholder="请输入商品价格" />
        </el-form-item>
        <!-- <el-form-item label="实际价格" prop="price">
          <el-input type="number" v-model="form.price" placeholder="请输入实际价格" />
        </el-form-item> -->
        <el-form-item label="库存" prop="stock">
          <el-input type="number" v-model="form.stock" placeholder="请输入库存" />
        </el-form-item>
        <el-form-item label="是否热门">
          <el-radio-group v-model="form.isHot">
            <el-radio
              v-for="dict in dict.type.is_hot"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品上架状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.p_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看库存弹窗 -->
    <el-dialog title="查看库存" :visible.sync="openProductKeyListDialog" width="800px" append-to-body>
        <el-form :model="productKeyListQueryParams" ref="productKeyQueryForm" :inline="true" label-width="68px">
          <el-form-item label="卡密" prop="cardKey">
            <el-input
              v-model="productKeyListQueryParams.cardKey"
              placeholder="请输入卡密"
              clearable
              size="small"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleProductKeyQuery">搜索</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="productKeyListLoading" :data="productKeyList" >
          <el-table-column label="卡密唯一标识" align="center" prop="prefixKey" />
          <el-table-column label="卡密" align="center" prop="cardKey" />
          <el-table-column label="是否售卖" align="center" prop="isSell">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.pk_is_seller" :value="scope.row.isSell"/>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" />
          <el-table-column label="修改时间" align="center" prop="updateTime" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="productKeyHandleUpdate(scope.row)"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="productKeyHandleDelete(scope.row)"
                v-hasPermi="['system:product:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="productKeyListTotal"
          :page.sync="productKeyListQueryParams.pageNo"
          :limit.sync="productKeyListQueryParams.pageSize"
          @pagination="getProductKeyList"
        />
    </el-dialog>

    <!-- 录入库存弹窗 -->
    <el-dialog title="录入库存" :visible.sync="openProductKeyAddDialog" width="1200px" append-to-body>
      <el-form ref="productKeyAddForm" :model="productKeyAddForm" :rules="productKeyAddRules" label-width="80px">
        <el-form-item label="分隔符" prop="separate">
          <el-input v-model="productKeyAddForm.separate" placeholder="请输入分隔符" />
        </el-form-item>
        <el-form-item label="卡密" prop="key">
          <el-input v-model="productKeyAddForm.key"
            placeholder="请批量输入卡密" 
            type="textarea"
            resize="both"
            :autosize="{ minRows: 30 }" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitProductKeyAdd">确 定</el-button>
        <el-button @click="openProductKeyAddDialog = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改库存 -->
    <el-dialog title="修改库存" :visible.sync="openProductKeyUpdateDialog" width="500px" append-to-body>
      <el-form ref="productKeyUpdateForm" :model="productKeyUpdateForm" :rules="productKeyUpdateRules" label-width="80px">
        <el-form-item label="卡密" prop="cardKey">
          <el-input v-model="productKeyUpdateForm.cardKey" />
        </el-form-item>
        <el-form-item label="卡密状态" prop="isSell">
          <el-select v-model="productKeyUpdateForm.isSell" size="small">
            <el-option
              v-for="dict in dict.type.pk_is_seller"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitProductKeyUpdate">确 定</el-button>
        <el-button @click="openProductKeyUpdateDialog = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct, listProductKey, delProductKey, productKeyAdd, productKeyUpdateStatus } from "@/api/system/product";
import { getCategorys } from "@/api/system/category";
import { Loading } from 'element-ui'

export default {
  name: "Product",
  dicts: ['p_status', 'pk_is_seller', 'is_hot', 'product_type'],
  data() {
    return {
      selectProductId: null,

      productKeyList: [],
      productKeyListLoading: false,
      openProductKeyListDialog: false,
      productKeyListTotal: 0,
      productKeyListQueryParams: {
        // 商品ID
        productId: null,
        cardKey: null,
        pageNo: 1,
        pageSize: 10
      },

      openProductKeyAddDialog: false,
      productKeyAddForm: {
        separate: "----",
        key: null
      },
      productKeyAddRules: {
        separate: [
          { required: true, message: "分隔符不能为空", trigger: "blur" }
        ],
        key: [
          { required: true, message: "卡密不能为空", trigger: "blur" }
        ]
      },

      openProductKeyUpdateDialog: false,
      productKeyUpdateForm: {
        id: null,
        cardKey: null,
        isSell: null
      },
      productKeyUpdateRules: {
        cardKey: [
          { required: true, message: "卡密不能为空", trigger: "blur" }
        ],
        isSell: [
          { required: true, message: "卡密状态不能为空", trigger: "blur" }
        ]
      },

      categroys: [],
      
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        name: null,
        intro: null,
        categoryId: null,
        cover: null,
        detail: null,
        originalPrice: null,
        price: null,
        stock: null,
        status: null,
      },
      // 表单参数
      form: {
        status: 'Y'
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "商品名不能为空", trigger: "blur" }
        ],
        intro: [
          { required: true, message: "商品简介不能为空", trigger: "blur" }
        ],
        categoryId: [
          { required: true, message: "关联分类id不能为空", trigger: "blur" }
        ],
        detail: [
          { required: true, message: "商品详情不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "商品价格不能为空", trigger: "blur" }
        ],
        stock: [
          { required: true, message: "库存不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "商品上架状态不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    getCategorys().then(res => {
      this.categroys = res.result
    })
  },
  methods: {
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.total = parseInt(response.total);
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        intro: null,
        type: null,
        categoryId: null,
        cover: null,
        detail: null,
        originalPrice: null,
        price: null,
        stock: null,
        status: 0,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProduct(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if(this.form.cover == undefined || this.form.cover == null || this.form.cover == ''){
        this.$modal.msgWarning("请上传商品图片");
        return 
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.originalPrice = this.form.price
          if (this.form.id != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品编号为"' + ids + '"的数据项？').then(function() {
        return delProduct(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    },
    /** 打开库存查看弹窗 */
    openProductKeyList(row) {
      this.selectProductId = row.id
      this.productKeyListQueryParams.productId = row.id
      this.openProductKeyListDialog = true
      this.getProductKeyList()
    },
    /** 打开录入库存弹窗 */
    openProductKeyAdd(row){
      this.selectProductId = row.id
      this.openProductKeyAddDialog = true
    },
    /**根据商品ID查询库存列表信息 */
    getProductKeyList(){
      this.productKeyListLoading = true;
      listProductKey(this.productKeyListQueryParams).then(response => {
        this.productKeyList = response.result.records;
        this.productKeyListTotal = parseInt(response.result.total);
        this.productKeyListLoading = false;
      });
    },
    /** 库存删除操作 */
    productKeyHandleDelete(row) {
      this.$modal.confirm('是否确认删除库存卡密唯一标识为"' + row.prefixKey + '"的数据项？').then(function() {
        return delProductKey([row.id]);
      }).then(() => {
        this.getProductKeyList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 库存添加卡密 */
    submitProductKeyAdd(){
      var submitLoading = Loading.service({ text: "正在添加", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
      var addProductKeys = []
      this.productKeyAddForm.key.split("\n").forEach(i => {
        let temp = {
          key: i,
          productId: this.selectProductId,
          separate: this.productKeyAddForm.separate
        }
        addProductKeys.push(temp)
      });
      productKeyAdd(addProductKeys).then(res => {
        this.$modal.msgSuccess(res.result);
        this.openProductKeyAddDialog = false
      }).finally(() => {
        submitLoading.close();
      })
    },
    uploadImage(imgUrl){
      this.form.cover = imgUrl.split(",")[0]
    },
    /** 修改库存卡密信息 */
    productKeyHandleUpdate(row){
      this.productKeyUpdateForm.id = row.id
      this.productKeyUpdateForm.cardKey = row.cardKey
      this.productKeyUpdateForm.isSell = row.isSell
      this.openProductKeyUpdateDialog = true
    },
    submitProductKeyUpdate(){
      if(this.productKeyUpdateForm.isSell === 'N'){
        this.$modal.msgWarning('暂不支持修改成未售卖状态');
        return 
      }
      productKeyUpdateStatus([this.productKeyUpdateForm.id]).then(res => {
         this.$modal.msgSuccess(res.result);
         this.getProductKeyList()
         this.openProductKeyUpdateDialog = false
      })
    },
    handleProductKeyQuery(){
      this.getProductKeyList()
    }
  }
};
</script>
<style>
.detail img{
  width: 100%;
}
</style>
